/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.testis.utils.middleware;

import java.util.LinkedList;
import org.orm.PersistentException;
import org.orm.PersistentTransaction;
import org.testis.orm.classes.T_label_filters;
import org.testis.orm.classes.T_label_filtersCriteria;
import org.testis.orm.classes.T_label_filtersFactory;

/**
 * 
 * @author selcuk
 */
public class LabelFilterDataHandler extends DbConnectionSupplier {

    public T_label_filters getLabelFilterById(int id) {
	T_label_filters result = null;
	try {
	    T_label_filtersCriteria criteria = new T_label_filtersCriteria();
	    criteria.id.eq(id);
	    result = criteria.uniqueT_label_filters();
	} catch (PersistentException ex) {
	}
	return result;
    }

    public int addLabelFilter(String name, String expression) {
	int result = 0;
	try {
	    PersistentTransaction t = openDBConnection().beginTransaction();
	    try {
		T_label_filters obj = new T_label_filters();
		obj.setName(name);
		obj.setFilterExpression(expression);
		obj.save();
		t.commit();
		result = obj.getId();
	    } catch (PersistentException ex) {
		t.rollback();
	    } finally {
		closeDBConnection();
	    }
	} catch (PersistentException ex) {
	}
	return result;
    }

    public boolean saveLabelFilter(int id, String name, String expression) {
	boolean result = false;
	try {
	    PersistentTransaction t = openDBConnection().beginTransaction();
	    try {
		T_label_filters obj = getLabelFilterById(id);
		if (obj == null) {
		    obj = new T_label_filters();
		}
		obj.setName(name);
		obj.setFilterExpression(expression);
		obj.save();
		t.commit();
		result = true;
	    } catch (PersistentException ex) {
		t.rollback();
	    } finally {
		closeDBConnection();
	    }

	} catch (PersistentException ex) {
	}
	return result;
    }

    public boolean removeLabeFilter(int id) {
	boolean result = false;
	try {
	    PersistentTransaction t = openDBConnection().beginTransaction();
	    try {
		T_label_filters obj = getLabelFilterById(id);
		result = obj.delete();
		t.commit();
	    } catch (PersistentException ex) {
		t.rollback();
	    } finally {
		closeDBConnection();
	    }
	} catch (PersistentException ex) {
	}
	return result;
    }

    public T_label_filters[] getLabelFiltersAsArray() {
	T_label_filters[] result = null;
	try {
	    result = T_label_filtersFactory.listT_label_filtersByQuery(null,
		    null);
	} catch (PersistentException ex) {
	}
	return result;
    }

    public LinkedList<T_label_filters> getLabelFiltersAsList() {
	LinkedList<T_label_filters> result = new LinkedList<T_label_filters>();
	T_label_filters[] arr = getLabelFiltersAsArray();
	if (arr != null && arr.length > 0) {
	    for (int i = 0; i < arr.length; i++) {
		result.add(arr[i]);
	    }
	}
	return result;
    }
}
